<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 产品溯源管理
 *
 * @icon fa fa-search
 * @remark 产品生产溯源系统，生成溯源码关联全生产过程
 */
class Traceability extends Backend
{
    /**
     * Traceability模型对象
     * @var \app\admin\model\scanwork\Traceability
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Traceability;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['order', 'product', 'model', 'customer'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取溯源摘要信息
        $summary = $row->getTraceSummary();
        
        // 获取详细溯源信息
        $details = $row->getTraceDetails();
        
        $this->view->assign('row', $row);
        $this->view->assign('summary', $summary);
        $this->view->assign('details', $details);
        
        return $this->view->fetch();
    }

    /**
     * 添加溯源记录
     */
    public function add()
    {
        // 获取订单列表
        $orderList = \app\admin\model\scanwork\Order::where('status', 2) // 只选择已完成的订单
            ->column('order_no', 'id');
        $this->view->assign('orderList', $orderList);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 创建溯源记录
     */
    public function create()
    {
        // 获取订单列表
        $orderList = \app\admin\model\scanwork\Order::where('status', 2) // 只选择已完成的订单
            ->column('order_no', 'id');
        $this->view->assign('orderList', $orderList);

        if ($this->request->isPost()) {
            $orderId = $this->request->post('order_id');
            
            if (!$orderId) {
                $this->error('请选择订单');
            }
            
            try {
                $result = $this->model->batchCreateTraceabilities($orderId);
                
                $message = "溯源记录创建完成！成功：{$result['success_count']}条，失败：{$result['error_count']}条";
                if (!empty($result['errors'])) {
                    $message .= "\n错误详情：\n" . implode("\n", $result['errors']);
                }
                
                $this->success($message);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
        }
        
        return $this->view->fetch();
    }

    /**
     * 更新溯源记录
     */
    public function update($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $traceability = $this->model->get($ids);
        if (!$traceability) {
            $this->error('溯源记录不存在');
        }
        
        try {
            $traceability->updateTraceability();
            $this->success('溯源记录更新成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 批量更新溯源记录
     */
    public function batchUpdate()
    {
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error('请选择要更新的记录');
        }
        
        $successCount = 0;
        $errorCount = 0;
        $errors = [];
        
        foreach ($ids as $id) {
            try {
                $traceability = $this->model->get($id);
                if ($traceability) {
                    $traceability->updateTraceability();
                    $successCount++;
                }
            } catch (Exception $e) {
                $errorCount++;
                $errors[] = "ID {$id}: " . $e->getMessage();
            }
        }
        
        $message = "批量更新完成！成功：{$successCount}条，失败：{$errorCount}条";
        if (!empty($errors)) {
            $message .= "\n错误详情：\n" . implode("\n", $errors);
        }
        
        $this->success($message);
    }

    /**
     * 扫码查询溯源信息
     */
    public function scan()
    {
        $traceCode = $this->request->get('trace_code');
        
        if (!$traceCode) {
            $this->error('溯源码不能为空');
        }
        
        $traceability = $this->model->where('trace_code', $traceCode)->find();
        if (!$traceability) {
            $this->error('溯源码不存在');
        }
        
        // 获取溯源摘要信息
        $summary = $traceability->getTraceSummary();
        
        $this->view->assign('traceability', $traceability);
        $this->view->assign('summary', $summary);
        
        return $this->view->fetch();
    }

    /**
     * 获取溯源详细信息（API接口）
     */
    public function getTraceInfo()
    {
        $traceCode = $this->request->get('trace_code');
        
        if (!$traceCode) {
            $this->error('溯源码不能为空');
        }
        
        $traceability = $this->model->where('trace_code', $traceCode)->find();
        if (!$traceability) {
            $this->error('溯源码不存在');
        }
        
        // 获取详细溯源信息
        $details = $traceability->getTraceDetails();
        
        $this->success('', null, $details);
    }

    /**
     * 生成溯源二维码
     */
    public function generateQrCode($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $traceability = $this->model->get($ids);
        if (!$traceability) {
            $this->error('溯源记录不存在');
        }
        
        try {
            // 生成二维码内容
            $qrContent = url('/admin/scanwork/traceability/scan', ['trace_code' => $traceability->trace_code], true, true);
            
            // 使用二维码生成库生成二维码图片
            $qrCode = new \Endroid\QrCode\QrCode($qrContent);
            $qrCode->setSize(300);
            $qrCode->setMargin(10);
            
            // 生成图片
            $imagePath = 'uploads/qrcode/traceability_' . $traceability->trace_code . '.png';
            $fullPath = ROOT_PATH . 'public/' . $imagePath;
            
            // 确保目录存在
            $dir = dirname($fullPath);
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            
            $qrCode->writeFile($fullPath);
            
            $this->success('二维码生成成功', '', [
                'qr_content' => $qrContent,
                'qr_image' => $imagePath
            ]);
            
        } catch (Exception $e) {
            $this->error('二维码生成失败：' . $e->getMessage());
        }
    }

    /**
     * 下载溯源报告
     */
    public function downloadReport($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $traceability = $this->model->get($ids);
        if (!$traceability) {
            $this->error('溯源记录不存在');
        }
        
        try {
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            
            // 设置标题
            $sheet->setCellValue('A1', '产品溯源报告');
            $sheet->mergeCells('A1:F1');
            $sheet->setCellValue('A2', '溯源码：' . $traceability->trace_code);
            $sheet->mergeCells('A2:F2');
            
            // 获取溯源信息
            $summary = $traceability->getTraceSummary();
            $details = $traceability->getTraceDetails();
            
            // 基本信息
            $row = 4;
            $sheet->setCellValue('A' . $row, '订单号：');
            $sheet->setCellValue('B' . $row, $summary['order_no']);
            $row++;
            
            $sheet->setCellValue('A' . $row, '客户名称：');
            $sheet->setCellValue('B' . $row, $summary['customer_name']);
            $row++;
            
            $sheet->setCellValue('A' . $row, '产品名称：');
            $sheet->setCellValue('B' . $row, $summary['product_name']);
            $row++;
            
            $sheet->setCellValue('A' . $row, '产品型号：');
            $sheet->setCellValue('B' . $row, $summary['model_name']);
            $row++;
            
            $sheet->setCellValue('A' . $row, '生产开始时间：');
            $sheet->setCellValue('B' . $row, $summary['production_start_time']);
            $row++;
            
            $sheet->setCellValue('A' . $row, '生产结束时间：');
            $sheet->setCellValue('B' . $row, $summary['production_end_time']);
            $row++;
            
            $sheet->setCellValue('A' . $row, '总数量：');
            $sheet->setCellValue('B' . $row, $summary['total_quantity']);
            $row++;
            
            $sheet->setCellValue('A' . $row, '合格数量：');
            $sheet->setCellValue('B' . $row, $summary['qualified_quantity']);
            $row++;
            
            $sheet->setCellValue('A' . $row, '质量合格率：');
            $sheet->setCellValue('B' . $row, $summary['quality_rate'] . '%');
            $row++;
            
            // 生产过程
            $row += 2;
            $sheet->setCellValue('A' . $row, '生产过程记录');
            $sheet->mergeCells('A' . $row . ':F' . $row);
            $row++;
            
            $sheet->setCellValue('A' . $row, '工序名称');
            $sheet->setCellValue('B' . $row, '分配数量');
            $sheet->setCellValue('C' . $row, '完成数量');
            $sheet->setCellValue('D' . $row, '实际工时');
            $sheet->setCellValue('E' . $row, '开始时间');
            $sheet->setCellValue('F' . $row, '结束时间');
            $row++;
            
            foreach ($details['production_process']['processes'] as $process) {
                $sheet->setCellValue('A' . $row, $process['process_name']);
                $sheet->setCellValue('B' . $row, $process['allocated_quantity']);
                $sheet->setCellValue('C' . $row, $process['reported_quantity']);
                $sheet->setCellValue('D' . $row, $process['actual_hours']);
                $sheet->setCellValue('E' . $row, $process['start_time'] ? date('Y-m-d H:i:s', $process['start_time']) : '');
                $sheet->setCellValue('F' . $row, $process['end_time'] ? date('Y-m-d H:i:s', $process['end_time']) : '');
                $row++;
            }
            
            // 员工记录
            $row += 2;
            $sheet->setCellValue('A' . $row, '员工记录');
            $sheet->mergeCells('A' . $row . ':F' . $row);
            $row++;
            
            $sheet->setCellValue('A' . $row, '员工姓名');
            $sheet->setCellValue('B' . $row, '工序名称');
            $sheet->setCellValue('C' . $row, '分配数量');
            $sheet->setCellValue('D' . $row, '完成数量');
            $sheet->setCellValue('E' . $row, '工作小时');
            $sheet->setCellValue('F' . $row, '完成时间');
            $row++;
            
            foreach ($details['employee_records'] as $employee) {
                $sheet->setCellValue('A' . $row, $employee['user_name']);
                $sheet->setCellValue('B' . $row, $employee['process_name']);
                $sheet->setCellValue('C' . $row, $employee['allocated_quantity']);
                $sheet->setCellValue('D' . $row, $employee['completed_quantity']);
                $sheet->setCellValue('E' . $row, $employee['total_hours']);
                $sheet->setCellValue('F' . $row, $employee['completion_time'] ? date('Y-m-d H:i:s', $employee['completion_time']) : '');
                $row++;
            }
            
            // 设置列宽
            $sheet->getColumnDimension('A')->setWidth(20);
            $sheet->getColumnDimension('B')->setWidth(20);
            $sheet->getColumnDimension('C')->setWidth(15);
            $sheet->getColumnDimension('D')->setWidth(15);
            $sheet->getColumnDimension('E')->setWidth(20);
            $sheet->getColumnDimension('F')->setWidth(20);
            
            // 设置样式
            $sheet->getStyle('A1:F1')->getFont()->setBold(true)->setSize(14);
            $sheet->getStyle('A2:F2')->getFont()->setBold(true);
            
            // 输出文件
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $filename = '产品溯源报告_' . $traceability->trace_code . '_' . date('YmdHis') . '.xlsx';
            
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            
            $writer->save('php://output');
            exit;
            
        } catch (Exception $e) {
            $this->error('报告生成失败：' . $e->getMessage());
        }
    }

    /**
     * 溯源统计报表
     */
    public function report()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        
        // 获取溯源统计
        $where = [];
        if ($startDate) {
            $where['createtime'] = ['>=', strtotime($startDate)];
        }
        if ($endDate) {
            $where['createtime'] = ['<=', strtotime($endDate . ' 23:59:59')];
        }
        
        $traceabilities = $this->model->with(['order', 'product', 'model', 'customer'])
            ->where($where)
            ->select();
        
        $stats = [
            'total_count' => count($traceabilities),
            'normal_count' => $traceabilities->where('status', 1)->count(),
            'abnormal_count' => $traceabilities->where('status', 0)->count(),
            'products' => [],
            'customers' => []
        ];
        
        // 按产品统计
        foreach ($traceabilities as $trace) {
            $productName = $trace->product->name;
            if (!isset($stats['products'][$productName])) {
                $stats['products'][$productName] = 0;
            }
            $stats['products'][$productName]++;
        }
        
        // 按客户统计
        foreach ($traceabilities as $trace) {
            $customerName = $trace->customer->customer_name;
            if (!isset($stats['customers'][$customerName])) {
                $stats['customers'][$customerName] = 0;
            }
            $stats['customers'][$customerName]++;
        }
        
        $this->view->assign('stats', $stats);
        $this->view->assign('traceabilities', $traceabilities);
        $this->view->assign('startDate', $startDate);
        $this->view->assign('endDate', $endDate);
        
        return $this->view->fetch();
    }

    /**
     * 自动创建溯源记录（定时任务）
     */
    public function autoCreate()
    {
        try {
            // 获取已完成的订单
            $completedOrders = \app\admin\model\scanwork\Order::where('status', 2)->select();
            
            $successCount = 0;
            $errorCount = 0;
            $errors = [];
            
            foreach ($completedOrders as $order) {
                try {
                    // 检查是否已有溯源记录
                    $existing = $this->model->where('order_id', $order->id)->find();
                    if (!$existing) {
                        $result = $this->model->batchCreateTraceabilities($order->id);
                        $successCount += $result['success_count'];
                        $errorCount += $result['error_count'];
                        $errors = array_merge($errors, $result['errors']);
                    }
                } catch (Exception $e) {
                    $errorCount++;
                    $errors[] = "订单【{$order->order_no}】: " . $e->getMessage();
                }
            }
            
            $message = "自动创建溯源记录完成！成功：{$successCount}条，失败：{$errorCount}条";
            if (!empty($errors)) {
                $message .= "\n错误详情：\n" . implode("\n", $errors);
            }
            
            $this->success($message);
            
        } catch (Exception $e) {
            $this->error('自动创建失败：' . $e->getMessage());
        }
    }
}
